<template>
	<el-dialog :title="titleMap[mode]" v-model="visible" :width="700" destroy-on-close @closed="$emit('closed')">
		<el-form :model="form" :rules="rules" ref="dialogForm" label-width="60px" label-position="right" class="pt-11 border-t-1 border-t-gray-300">
			<el-form-item :label="$t('platform.name')" prop="name">
				<el-input v-model="form.name" clearable></el-input>
			</el-form-item>
			<el-form-item :label="$t('common.sort')" prop="sort">
				<el-input-number v-model="form.sort" controls-position="right" :min="1" style="width: 100%"></el-input-number>
			</el-form-item>
			<el-form-item :label="$t('common.status')" prop="status">
				<el-switch v-model="form.status" :active-value="1" :inactive-value="0"></el-switch>
			</el-form-item>
			<el-form-item :label="$t('common.describe')" prop="describe">
				<el-input v-model="form.describe" clearable type="textarea"></el-input>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="visible = false">{{ $t('common.cancle') }}</el-button>
			<el-button type="primary" :loading="isSaveing" @click="submit()">{{ $t('common.save') }}</el-button>
		</template>
	</el-dialog>
</template>
<script setup lang="ts">
	// 导入用于触发自定义事件的 emit 函数
	const emit = defineEmits(['success', 'closed'])
	// 定义模式（add 或 edit），控制表单标题和提交方式
	const mode = ref<string>('add')
	// 定义模式对应的标题映射
	const titleMap = reactive<Record<string, string>>({
		add: lang.global.t('common.add') + lang.global.t('platform.platform'),
		edit: lang.global.t('common.edit') + lang.global.t('platform.platform')
	})
	// 控制弹窗显示与隐藏的标志
	const visible = ref(false)
	// 保存按钮加载状态，防止重复提交
	const isSaveing = ref(false)
	// 表单的引用，用于表单验证
	const dialogForm = ref()
	// 表单数据的初始化值
	const form = reactive({
		id: 0,
		name: '',
		describe: '',
		sort: 100,
		status: 1
	})
	// 表单校验规则，名称字段必填
	const rules = reactive({
		name: [{ required: true, message: lang.global.t('platform.nameError'), trigger: 'blur' }]
	})
	// 打开弹窗函数，接受操作模式参数（add 或 edit）
	const open = (value: string) => ((mode.value = value), (visible.value = true))
	// 表单提交函数，根据模式调用不同的接口
	const submit = () => {
		dialogForm.value.validate(async (valid: boolean) => {
			if (!valid) return false
			isSaveing.value = true
			const res = mode.value === 'add' ? await api.platform.add.post(form) : await api.platform.edit.post(form)
			if (res.code === 200) {
				emit('success', mode.value, form)
				visible.value = false
				ElMessage.success(res.message)
			} else {
				ElMessage.error(res.message)
			}
			isSaveing.value = false
		})
	}
	// 设置表单数据的函数，将传入的数据合并到表单中
	const setData = (data: { id: number; name: string; describe: string; sort: number; status: number }) => Object.assign(form, data)
	// 暴露给父组件的方法，用于控制弹窗和设置数据
	defineExpose({ open, setData })
</script>
